package me.jiatao.usercenter.ui.activity

import android.os.Bundle
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_register.*
import me.jiatao.baselibrary.ext.enable
import me.jiatao.baselibrary.ext.onClick
import me.jiatao.baselibrary.ext.textString
import me.jiatao.baselibrary.ui.activity.BaseMvpActivity
import me.jiatao.baselibrary.ext.checkPhoneNum
import me.jiatao.usercenter.R
import me.jiatao.usercenter.injection.component.DaggerUserComponent
import me.jiatao.usercenter.mvp.presenter.RegisterPresenter
import me.jiatao.usercenter.mvp.view.RegisterView
import org.jetbrains.anko.toast

class RegisterActivity : BaseMvpActivity<RegisterView,RegisterPresenter>(), RegisterView, View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        initView()
    }

    override fun injectComponent() {
        DaggerUserComponent.builder()
            .activityComponent(mActivityComponent)
            .build()
            .inject(this)
    }


    /**
     *  初始化视图
     */
    private fun initView() {

        mRegisterBtn.enable(mMobileEt) { isBtnEnable() }
        mRegisterBtn.enable(mVerifyCodeEt) { isBtnEnable() }
        mRegisterBtn.enable(mPwdEt) { isBtnEnable() }
        mRegisterBtn.enable(mPwdConfirmEt) { isBtnEnable() }

        mVerifyCodeBtn.onClick(this)
        mRegisterBtn.onClick(this)
    }

    /**
     * 判断注册按钮是否可用
     */
    private fun isBtnEnable(): Boolean {
        return mMobileEt.text.isNullOrEmpty().not() &&
                mVerifyCodeEt.text.isNullOrEmpty().not() &&
                mPwdEt.text.isNullOrEmpty().not() &&
                mPwdConfirmEt.text.isNullOrEmpty().not()
    }

    /**
     * 点击事件
     */
    override fun onClick(view: View) {
        when (view.id) {
            R.id.mVerifyCodeBtn -> {
                sendVerifyNumber()
            }

            R.id.mRegisterBtn -> {
                mPresenter.register(
                    mMobileEt.textString(),
                    mPwdEt.textString(),
                    mVerifyCodeEt.textString()
                )
            }
        }
    }

    /**
     * 发送验证码逻辑
     */
    private fun sendVerifyNumber() {
        if (checkPhoneNum(mMobileEt.textString())) {
            mVerifyCodeBtn.requestSendVerifyNumber()
            toast("发送验证成功")
        } else {
            toast("请输入正确验证码")
        }
    }


    override fun onRegisterResult(result: String) {
        Toast.makeText(this, result, Toast.LENGTH_LONG).show()
    }
}